package com.bang.study.day05.leetcode;


/**
 * @Auther: Bang
 * @Date: 2019/9/17 0017 08:54
 * @Description: 字典树 前缀树 基于TreeMap
 */
public class Trie {

    class TrieNode{
        private boolean isEnd;

        private TrieNode[] links;

        public TrieNode() {
            links = new TrieNode[26];
        }

        public boolean contains(char ch) {
            return links[ch - 'a'] != null;
        }

        public void put(char ch, TrieNode node) {
            links[ch -'a'] = node;
        }

        public TrieNode get(char ch) {
           return links[ch -'a'];
        }

        public boolean isEnd() {
            return isEnd;
        }

        public void setEnd(boolean flag) {
            isEnd = flag;
        }
    }

    private TrieNode root;

    /** Initialize your data structure here. */
    public Trie() {
        this.root = new TrieNode();
    }

    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode curr = root;
        for (int i = 0; i <word.length() ; i++) {
            char c = word.charAt(i);
            if (!curr.contains(c)) {
                curr.put(c, new TrieNode());
            }
            curr = curr.get(c);

        }
        curr.setEnd(true);
    }

    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode node = searchPrefix(word);
        return node != null && node.isEnd;
    }

    private TrieNode searchPrefix(String word){
        TrieNode curr = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (!curr.contains(c)) {
                return null;
            }
            curr = curr.get(c);
        }
        return curr;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode node = searchPrefix(prefix);
        return node != null;
    }

    public static void main(String[] args) {
        Trie trie = new Trie();

        trie.insert("apple");
        trie.search("apple");   // 返回 true
        trie.search("app");     // 返回 false
        trie.startsWith("app"); // 返回 true
        trie.insert("app");
        trie.search("app");     // 返回 true

    }
}
/**
 * java.lang.NullPointerException
 *   at line 89, Trie.insert
 *   at line 57, __Driver__.__helperSelectMethod__
 *   at line 83, __Driver__.__helper__
 *   at line 104, __Driver__.main
 */
